package com.sise.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.sise.bean.CodeMsg;
import com.sise.bean.WeChatSession;
import com.sise.entity.User;
import com.sise.mapper.UserMapper;
import com.sise.service.IUserService;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author zj
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public CodeMsg<String> onLogin(String code, String nickName, String avatarUrl, Integer gender) {
        //用户的唯一标识
        String openId = "";
        String appid = "wx54da097266287a37";
        String secret = "400c374d7b3a6f4df5653003444dfbc3";
        //微信的接口
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid +
                "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        //进行网络请求,访问url接口
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        //根据返回值进行后续操作
        int tap = 200;
        String msg;
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            String sessionData = responseEntity.getBody();
            Gson gson = new Gson();
            //解析从微信服务器获得的openid和session_key
            WeChatSession weChatSession = gson.fromJson(sessionData, WeChatSession.class);
            //获取用户的唯一标识
            openId = weChatSession.getOpenid();
            //获取会话秘钥
            if ("".equals(openId)) {
                return new CodeMsg<String>().setCode(401).setMsg("openid不存在").setData("");
            }
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(User::getOpenId, openId);
            Integer count = userMapper.selectCount(queryWrapper);
            if (count == 0) {
                userMapper.insert(new User().setOpenId(openId).setAvatarUrl(avatarUrl).setUserGender(gender).setUserName(nickName));
                msg = "创建用户成功";
            } else {
                User user = userMapper.selectOne(queryWrapper);
                if (user.getAvatarUrl().equals(avatarUrl) && user.getUserGender().equals(gender) && user.getUserName().equals(nickName)) {
                    msg = "信息未修改";
                } else {
                    userMapper.updateById(user.setAvatarUrl(avatarUrl).setUserGender(gender).setUserName(nickName));
                    msg = "信息修改成功";
                }
            }
        } else {
            msg = "登陆失败";
            tap = 400;
        }
        return new CodeMsg<String>().setCode(tap).setMsg(msg).setData(openId);
    }

    @Override
    public CodeMsg<List<User>> getAllUser() {
        return new CodeMsg<List<User>>().setCode(200).setMsg("获取成功").setData(userMapper.selectList(null));
    }

    @Override
    public CodeMsg<String> updateUserById(User user) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.lambda().eq(User::getOpenId, user.getOpenId());
        final User getUser = userMapper.selectOne(userQueryWrapper);
        if (getUser == null) {
            return new CodeMsg<String>().setCode(400).setMsg("用户不存在");
        }
        final int i = userMapper.updateById(user);
        if (i == 1) {
            return new CodeMsg<String>().setCode(200).setMsg("更新成功");
        }
        return new CodeMsg<String>().setCode(401).setMsg("更新失败");
    }

    @Override
    public CodeMsg<String> getOpenId(String code) {
        //用户的唯一标识
        String openId = "";
        String appid = "wx54da097266287a37";
        String secret = "400c374d7b3a6f4df5653003444dfbc3";
        //微信的接口
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid +
                "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        //进行网络请求,访问url接口
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        //根据返回值进行后续操作
        int tap = 200;
        String msg;
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            String sessionData = responseEntity.getBody();
            Gson gson = new Gson();
            //解析从微信服务器获得的openid和session_key
            WeChatSession weChatSession = gson.fromJson(sessionData, WeChatSession.class);
            //获取用户的唯一标识
            openId = weChatSession.getOpenid();
            //获取会话秘钥
            if ("".equals(openId)) {
                return new CodeMsg<String>().setCode(401).setMsg("openid不存在").setData("");
            }
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(User::getOpenId, openId);
            Integer count = userMapper.selectCount(queryWrapper);
            if (count == 0) {
                userMapper.insert(new User().setOpenId(openId));
                msg = "创建用户成功";
            } else{
                msg = "用户已存在";
            }
        } else {
            msg = "登陆失败";
            tap = 400;
        }
        return new CodeMsg<String>().setCode(tap).setMsg(msg).setData(openId);
    }
}
